# -*- coding: utf-8 -*-
# standard
import os
import sys

# third

# local
_P_PATH =  os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _P_PATH not in sys.path:
    sys.path.append(_P_PATH)
from functions import *


"""
@Title:   
@File: 补全已下载音频尺寸.py
@Author: walle 2024年01日16日 16时20分35秒
@Version: 1.0.0
@Desc: 
"""


def get_hk02_videos():
    """
    获取爬虫服务器02上的所有视频信息。
    只能在hk01上运行
    """
    command = 'ls -l /mnt/projects/LRS3_m4a/*/* | grep "^-"'
    ssh = paramiko.SSHClient()  
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())  
    # 连接到远程Linux系统  
    ssh.connect(hostname="172.26.190.232", port=PORT, username="spider", password="jingying")    
    # 执行命令并获取输出  
    stdin, stdout, stderr = ssh.exec_command(command)  
    output = stdout.read().decode()  
    ssh.close()
    file_lines = output.split("\n")
    good_files, bad_files = ScpRecordOrm.format_remote_file_info(file_lines)
    return good_files, bad_files


def main(redownload: bool = True):
    """
    检查下载的音频文件是否都已经update 到hk02
    
    """
    warnings.warn("注意，此脚本运行之前，必须确保hk01本地没有未拷贝的音频文件，否则会造成数据失准")
    good_files, bad_files = get_hk02_videos()
    good_files = {k.split("/")[-1]: v for k, v in good_files.items()}
    db_session = new_db_session()
    query = db_session.query(MediaFileOrm).filter(and_(MediaFileOrm.audio_path != "", MediaFileOrm.need_audio == 1))
    num = 0
    num1 = 0
    for x in query:
        if x.key in good_files:
            if x.audio_size == 0:
                print(x)
            else:
                pass
        else:
            x.audio_path = ''
            num += 1
    db_session.commit()
    db_session.close()
    logger.debug(f"修正了 {num} 个需要重新下载的记录")


if __name__ == '__main__':
    main()
    pass